// pages/pingjia/pingjia.js

import config from './../../config';
import {
    toast,
    empty,
    message,
    session,
    getOpenId
} from './../../utils/helper';
import {
    submitEvaluation,
    wxPayment
} from './../../services/pingjia';
import qs from 'qs';
import WxValidate from './../../utils/validate';

//获取应用实例
const app = getApp();
//实例化本地缓存
const cookie = new session();

const btn = [{
        value: 6,
        background: "#FFF",
        color: "#333"
    },
    {
        value: 8,
        background: "#FFF",
        color: "#333"
    },
    {
        value: 18,
        background: "#FFF",
        color: "#333"
    },
    {
        value: 66,
        background: "#FFF",
        color: "#333"
    },
    {
        value: 99,
        background: "#FFF",
        color: "#333"
    },
    {
        value: 188,
        background: "#FFF",
        color: "#333"
    }
];
const star = [
    '../../images/Star-fill.png',
    '../../images/Star-fill.png',
    '../../images/Star-fill.png',
    '../../images/Star-fill.png',
    '../../images/Star-fill.png'
];


Page({

    /**
     * 页面的初始数据
     */
    data: {
        tip: true,
        errorMsg: [],
        disabled: false,
        starArray: star,
        btnArray: btn,
        star: 5,
        money: 0
    },

    //父级页面传递过来的表单参数
    params: {},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        //显示当前页面的转发按钮
        wx.showShareMenu({
            withShareTicket: true
        });
        if (empty(options)) {
            console.warn('同学：你这个样子直接打开，是木有办法提交的表单的！');
        } else {
            this.params = options;
        }
        this.initValidate();
    },

    //要付钱的评价
    submitForm1(params) {
        this.setData({
            errorMsg: [],
            tip: false,
            disabled: true
        });
        let that = this;
        submitEvaluation(params, {
            success: (res) => {
                wxPayment(res.data, {
                    success: () => {
                        message('评价成功', () => {
                            const len = getCurrentPages().length;
                            if (len > 1) {
                                wx.navigateBack({
                                    delta: 1
                                })
                            }
                        })
                    },
                    fail: () => {
                        message('支付失败,请重试')
                    },
                    complete: () => {
                        that.setData({
                            disabled: false
                        });
                    }
                });
            },
            fail: (res) => {
                that.setData({
                    disabled: false
                })
                message(res.msg)
            }
        });
    },

    //单纯评价
    submitForm2(params) {
        this.setData({
            errorMsg: [],
            tip: false,
            disabled: true
        });
        let that = this;
        submitEvaluation(params, {
            success: () => {
                message('评价成功', () => {
                    const len = getCurrentPages().length;
                    if (len > 1) {
                        wx.navigateBack({
                            delta: 1
                        })
                    }
                })
            },
            complete: () => {
                that.setData({
                    disabled: false
                });
            }
        });
    },

    //校验表单函数
    checkForm: function(e) {
        let params = e.detail.value;
        // 传入表单数据，调用验证方法
        if (this.WxValidate.checkForm(params)) {
            this.setData({
                errorMsg: [],
                tip: true,
            });
            if (!empty(params.moneyinput)) {
                if (params.moneyinput < 100) {
                    message('您输入的金额小于100')
                    return false;
                }
                params.money = params.moneyinput;
            }
            delete params.moneyinput;
            if (params.money > 0) {
                this.submitForm1(Object.assign(this.params, params))
            } else {
                this.submitForm2(Object.assign(this.params, params))
            }
        } else {
            let errors = this.WxValidate.validationErrors(),
                error = [];
            error[0] = errors[0];
            this.setData({
                errorMsg: error,
                tip: false,
            });
        }
    },

    //金额输入事件
    bindinput(e) {
        if (!empty(e.detail.value)) {
            return e.detail.value.match(/^\d+(?:\.\d{0,2})?/);
        }
    },

    //选择打赏金额
    btn_pay(e) {
        let money = e.currentTarget.dataset.value,
            that = this;
        this.data.btnArray.map((val, index) => {
            if (val.value == money) {
                if (that.data.btnArray[index].color != "#fff") {
                    that.data.btnArray[index] = Object.assign(val, {
                        background: "#34cc4d",
                        color: "#fff"
                    });
                } else {
                    that.data.btnArray[index] = Object.assign(val, {
                        background: "#fff",
                        color: "#333"
                    });
                    money = 0;
                }
            } else {
                that.data.btnArray[index] = Object.assign(val, {
                    background: "#fff",
                    color: "#333"
                })
            }
            that.setData({
                money: money,
                btnArray: that.data.btnArray
            });
        });
    },

    // 星星点击事件
    starTap: function(e) {
        let tempUserStars = this.data.starArray; // 暂存星星数组
        const index = e.currentTarget.dataset.index, // 获取当前点击的是第几颗星星
            len = tempUserStars.length; // 获取星星数组的长度
        for (var i = 0; i < len; i++) {
            if (i <= index) { // 小于等于index的是满心
                tempUserStars[i] = '../../images/Star-fill.png'
            } else { // 其他是空心
                tempUserStars[i] = '../../images/Star.png'
            }
        }
        // 重新赋值就可以显示了
        this.setData({
            starArray: tempUserStars,
            star: index + 1
        })
    },

    //初始化验证规则
    initValidate() {
        // 验证字段的规则
        const rules = {
            star: {
                required: true,
                number: true
            },
            body: {
                maxlength: 150
            },
            money: {
                number: true
            },
            moneyinput: {
                number: true,
                max: 100000
            }
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            star: {
                required: '请点选评价星级',
                number: '评价星级只能是数字'
            },
            body: {
                maxlength: '评价内容最大长度150个字符'
            },
            money: {
                number: '金额只能是数字'
            },
            moneyinput: {
                number: '金额只能是数字',
                max: '评价打赏10万封顶'
            }
        }
        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)
    }
})